package com.dz.utils;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

// Bean拷贝工具类
public class BeanCopyUtils {

    private BeanCopyUtils() {
    }

    // 单个对象的拷贝
    public static <V> V copyBean(Object source, Class<V> clazz) {
        V target = null;
        try {
            /*
             * getDeclaredConstructor()方法会根据他的参数对该类的构造函数进行搜索并返回对应的构造函数，
             * 没有参数就返回该类的无参构造函数，然后再通过newInstance进行实例化。*/
            target = clazz.getDeclaredConstructor().newInstance();
            // 对属性的拷贝，将source的属性拷贝给target
            BeanUtils.copyProperties(source, target);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return target;
    }

    // 对集合里的Bean进行拷贝
    public static <O,V> List<V> copyBeanList(List<O> sources, Class<V> clazz) {
        List<V> list = new ArrayList<>();
        for (Object source : sources) {
            V v = copyBean(source, clazz);
            list.add(v);
        }
        return list;
    }
}
